package com.example.demo.services;


import com.example.demo.identity.User;
import com.example.demo.mapper.UserMapper;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.EnumMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

@Service
public class UserService {

    enum Field {
        USERNAME, GEX, BIRTHDAY, COUNTRY, PROVINCE, CITY, SIGNATUREOFTHEINDIVIDUAL
    }

    private final static Logger logger = LoggerFactory.getLogger(UserService.class);

    //    初始化字段映射器    将 Consumer<Object> 改为 BiConsumer<User, Object>，这样可以将 User 实例作为第一个参数传递
    private final EnumMap<Field, BiConsumer<User, Object>> fieldSetters;

    private final UserMapper userMapper;

    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
        this.fieldSetters = new EnumMap<>(Field.class);
        // 将字段设置器映射到对应的 User 类的 setter 方法       因为类型不一致，所以在这里使用lambda表达式进行类型转换
        fieldSetters.put(Field.USERNAME, (user, object) -> user.setUsername((String) object));
        fieldSetters.put(Field.GEX, (user, object) -> user.setGex((String) object));
        fieldSetters.put(Field.BIRTHDAY, (user, object) -> user.setBirthday((String) object));
        fieldSetters.put(Field.COUNTRY, (user, object) -> user.setCountry((String) object));
        fieldSetters.put(Field.PROVINCE, (user, object) -> user.setProvince((String) object));
        fieldSetters.put(Field.CITY, (user, object) -> user.setCity((String) object));
        fieldSetters.put(Field.SIGNATUREOFTHEINDIVIDUAL, (user, object) -> user.setSignatureOfTheIndividual((String) object));
    }

    @Transactional
    public boolean updateUserInfo(String userId, Map<String, Object> updateFields) {
//        提取嵌套字段
        @SuppressWarnings("unchecked")
        Map<String, Object> fieldsMap = (Map<String, Object>) updateFields.get("updateFields");
        User user = new User();

//        通过userId获取用户信息
        User currentUser = userMapper.getUserByUUID(userId);
        if (currentUser == null) {
            throw new RuntimeException("用户不存在");
        }

//        遍历变更的字段，动态更新
        fieldsMap.forEach((field, newValue) -> {
            try {
                Field enumField = Field.valueOf(field.toUpperCase());
                BiConsumer<User, Object> setter = fieldSetters.get(enumField);
                if (setter != null) {
                    setter.accept(currentUser, newValue);
                }
            } catch (IllegalArgumentException e) {
                logger.info("忽略未知字段: {}", field);
            }
        });
//        保存更新到数据库
        int affectedROws = userMapper.dynamicUpdates(userId, currentUser);
        return affectedROws > 0;
    }

}
